const Fruit = require('../models/Fruit');
const Warehouse = require('../models/Warehouse');
const FruitWarehouse = require('../models/FruitWarehouse');

// 获取所有水果列表
const getAllFruits = async (req, res) => {
  try {
    const { search, warehouse_id } = req.query;
    
    let whereCondition = {};
    let includeCondition = [];
    
    // 如果有搜索关键词
    if (search) {
      whereCondition.name = {
        [require('sequelize').Op.like]: `%${search}%`
      };
    }
    
    // 包含仓库信息
    const warehouseInclude = {
      model: Warehouse,
      as: 'warehouses',
      attributes: ['id', 'name', 'location'],
      through: {
        attributes: ['quantity']
      }
    };
    
    // 如果按仓库筛选
    if (warehouse_id) {
      warehouseInclude.where = { id: warehouse_id };
    }
    
    includeCondition.push(warehouseInclude);
    
    const fruits = await Fruit.findAll({
      where: whereCondition,
      include: includeCondition,
      order: [['created_at', 'ASC']]
    });
    
    res.json({
      success: true,
      data: fruits
    });
  } catch (error) {
    console.error('获取水果列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取水果列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 根据ID获取单个水果
const getFruitById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const fruit = await Fruit.findByPk(id);
    
    if (!fruit) {
      return res.status(404).json({
        success: false,
        message: '水果不存在'
      });
    }
    
    res.json({
      success: true,
      data: fruit
    });
  } catch (error) {
    console.error('获取水果详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取水果详情失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 创建新水果
const createFruit = async (req, res) => {
  try {
    const { name, category, price, total_stock } = req.body;
    
    // 验证必填字段
    if (!name || !category || price === undefined || total_stock === undefined) {
      return res.status(400).json({
        success: false,
        message: '请提供所有必填字段'
      });
    }
    
    // 验证价格
    if (price < 0) {
      return res.status(400).json({
        success: false,
        message: '价格不能为负数'
      });
    }
    
    // 也可以添加价格上限验证
    if (price > 10000) {
      return res.status(400).json({
        success: false,
        message: '价格不能超过 10000'
      });
    }
    
    // 验证总库存
    if (total_stock < 0) {
      return res.status(400).json({
        success: false,
        message: '总库存不能为负数'
      });
    }
    
    // 创建水果（初始时，可用库存等于总库存，因为还未分配到任何仓库）
    const fruit = await Fruit.create({
      name,
      category,
      price,
      total_stock,
      stock: total_stock
    });
    
    // 重新查询包含仓库信息的水果
    const fruitWithWarehouses = await Fruit.findByPk(fruit.id, {
      include: [{
        model: Warehouse,
        as: 'warehouses',
        attributes: ['id', 'name', 'location'],
        through: {
          attributes: ['quantity']
        }
      }]
    });
    
    res.status(201).json({
      success: true,
      message: '创建成功',
      data: fruitWithWarehouses
    });
  } catch (error) {
    console.error('创建水果错误:', error);
    
    if (error.name === 'SequelizeValidationError') {
      return res.status(400).json({
        success: false,
        message: error.errors[0].message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '创建水果失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 更新水果信息
const updateFruit = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, category, price, total_stock } = req.body;
    
    // 查找水果
    const fruit = await Fruit.findByPk(id);
    
    if (!fruit) {
      return res.status(404).json({
        success: false,
        message: '水果不存在'
      });
    }
    
    // 验证价格
    if (price !== undefined && price < 0) {
      return res.status(400).json({
        success: false,
        message: '价格不能为负数'
      });
    }
    
    // 验证价格上限
    if (price !== undefined && price > 10000) {
      return res.status(400).json({
        success: false,
        message: '价格不能超过 10000'
      });
    }
    
    // 验证总库存
    if (total_stock !== undefined && total_stock < 0) {
      return res.status(400).json({
        success: false,
        message: '总库存不能为负数'
      });
    }
    
    // 如果修改总库存，需要检查是否小于已分配的数量
    if (total_stock !== undefined) {
      const allocatedQuantity = await FruitWarehouse.sum('quantity', {
        where: { fruit_id: id }
      }) || 0;
      
      if (total_stock < allocatedQuantity) {
        return res.status(400).json({
          success: false,
          message: `总库存 (${total_stock}) 不能小于已分配到仓库的数量 (${allocatedQuantity})`
        });
      }
      
      // 更新可用库存
      fruit.stock = total_stock - allocatedQuantity;
    }
    
    // 更新基本字段
    if (name !== undefined) fruit.name = name;
    if (category !== undefined) fruit.category = category;
    if (price !== undefined) fruit.price = price;
    if (total_stock !== undefined) fruit.total_stock = total_stock;
    
    await fruit.save();
    
    // 重新查询包含仓库信息的水果
    const fruitWithWarehouses = await Fruit.findByPk(id, {
      include: [{
        model: Warehouse,
        as: 'warehouses',
        attributes: ['id', 'name', 'location'],
        through: {
          attributes: ['quantity']
        }
      }]
    });
    
    res.json({
      success: true,
      message: '更新成功',
      data: fruitWithWarehouses
    });
  } catch (error) {
    console.error('更新水果错误:', error);
    
    if (error.name === 'SequelizeValidationError') {
      return res.status(400).json({
        success: false,
        message: error.errors[0].message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '更新水果失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 删除水果
const deleteFruit = async (req, res) => {
  try {
    const { id } = req.params;
    
    const fruit = await Fruit.findByPk(id);
    
    if (!fruit) {
      return res.status(404).json({
        success: false,
        message: '水果不存在'
      });
    }
    
    await fruit.destroy();
    
    res.json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除水果错误:', error);
    res.status(500).json({
      success: false,
      message: '删除水果失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 批量删除水果
const batchDeleteFruits = async (req, res) => {
  try {
    const { ids } = req.body;
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供要删除的水果ID列表'
      });
    }
    
    await Fruit.destroy({
      where: {
        id: ids
      }
    });
    
    res.json({
      success: true,
      message: `成功删除 ${ids.length} 个水果`
    });
  } catch (error) {
    console.error('批量删除水果错误:', error);
    res.status(500).json({
      success: false,
      message: '批量删除水果失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

module.exports = {
  getAllFruits,
  getFruitById,
  createFruit,
  updateFruit,
  deleteFruit,
  batchDeleteFruits
};

